class AuthManager {
    constructor() {
        this.apiBase = './api';
        this.initializeEventListeners();
        this.checkExistingAuth();
    }

    initializeEventListeners() {
        // 登录表单
        document.getElementById('loginFormElement').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleLogin();
        });

        // 注册表单
        document.getElementById('registerFormElement').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleRegister();
        });

        // 密码强度检测
        document.getElementById('registerPassword').addEventListener('input', (e) => {
            this.checkPasswordStrength(e.target.value);
        });

        // 确认密码验证
        document.getElementById('confirmPassword').addEventListener('input', (e) => {
            this.validatePasswordMatch();
        });

        // 实时输入验证
        this.setupInputValidation();
    }

    setupInputValidation() {
        const inputs = document.querySelectorAll('input');
        inputs.forEach(input => {
            input.addEventListener('blur', () => this.validateInput(input));
            input.addEventListener('input', () => this.clearInputError(input));
        });
    }

    async handleLogin() {
        const form = document.getElementById('loginFormElement');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        
        // 添加记住我选项
        data.remember_me = document.getElementById('rememberMe').checked;

        if (!this.validateLoginForm(data)) {
            return;
        }

        this.showLoading();
        
        try {
            const response = await this.apiRequest('auth.php?action=login', 'POST', data);
            
            if (response.success) {
                // 保存认证信息
                this.saveAuthData(response.data);
                this.showNotification('登录成功！', 'success');
                
                // 跳转到主页面
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1000);
            } else {
                this.showNotification(response.message || '登录失败', 'error');
            }
        } catch (error) {
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            this.hideLoading();
        }
    }

    async handleRegister() {
        const form = document.getElementById('registerFormElement');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        if (!this.validateRegisterForm(data)) {
            return;
        }

        this.showLoading();
        
        try {
            const response = await this.apiRequest('auth.php?action=register', 'POST', data);
            
            if (response.success) {
                // 保存认证信息
                this.saveAuthData(response.data);
                this.showNotification('注册成功！', 'success');
                
                // 跳转到主页面
                setTimeout(() => {
                    window.location.href = 'index.html';
                }, 1000);
            } else {
                if (response.errors) {
                    this.displayFormErrors(response.errors);
                } else {
                    this.showNotification(response.message || '注册失败', 'error');
                }
            }
        } catch (error) {
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            this.hideLoading();
        }
    }

    validateLoginForm(data) {
        let isValid = true;

        // 验证用户名/邮箱
        if (!data.login || data.login.trim().length === 0) {
            this.showInputError('loginUsername', '请输入用户名或邮箱');
            isValid = false;
        }

        // 验证密码
        if (!data.password || data.password.length === 0) {
            this.showInputError('loginPassword', '请输入密码');
            isValid = false;
        }

        return isValid;
    }

    validateRegisterForm(data) {
        let isValid = true;

        // 验证用户名
        if (!data.username || data.username.trim().length < 3) {
            this.showInputError('registerUsername', '用户名至少需要3个字符');
            isValid = false;
        } else if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(data.username)) {
            this.showInputError('registerUsername', '用户名只能包含字母、数字、下划线和中文');
            isValid = false;
        }

        // 验证邮箱
        if (!data.email || !this.isValidEmail(data.email)) {
            this.showInputError('registerEmail', '请输入有效的邮箱地址');
            isValid = false;
        }

        // 验证密码
        if (!data.password || data.password.length < 6) {
            this.showInputError('registerPassword', '密码至少需要6个字符');
            isValid = false;
        }

        // 验证确认密码
        if (data.password !== data.confirm_password) {
            this.showInputError('confirmPassword', '两次输入的密码不一致');
            isValid = false;
        }

        return isValid;
    }

    validateInput(input) {
        const value = input.value.trim();
        let isValid = true;
        let message = '';

        switch (input.id) {
            case 'registerUsername':
                if (value.length > 0 && value.length < 3) {
                    message = '用户名至少需要3个字符';
                    isValid = false;
                } else if (value.length > 0 && !/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(value)) {
                    message = '用户名只能包含字母、数字、下划线和中文';
                    isValid = false;
                }
                break;
            
            case 'registerEmail':
                if (value.length > 0 && !this.isValidEmail(value)) {
                    message = '请输入有效的邮箱地址';
                    isValid = false;
                }
                break;
            
            case 'registerPassword':
                if (value.length > 0 && value.length < 6) {
                    message = '密码至少需要6个字符';
                    isValid = false;
                }
                break;
            
            case 'confirmPassword':
                const password = document.getElementById('registerPassword').value;
                if (value.length > 0 && value !== password) {
                    message = '两次输入的密码不一致';
                    isValid = false;
                }
                break;
        }

        if (!isValid) {
            this.showInputError(input.id, message);
        } else {
            this.clearInputError(input);
        }

        return isValid;
    }

    validatePasswordMatch() {
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('confirmPassword').value;
        
        if (confirmPassword.length > 0) {
            if (password !== confirmPassword) {
                this.showInputError('confirmPassword', '两次输入的密码不一致');
            } else {
                this.clearInputError(document.getElementById('confirmPassword'));
            }
        }
    }

    checkPasswordStrength(password) {
        const strengthElement = document.getElementById('passwordStrength');
        const strengthFill = strengthElement.querySelector('.strength-fill');
        const strengthText = strengthElement.querySelector('.strength-text');
        
        if (password.length === 0) {
            strengthElement.classList.remove('show');
            return;
        }
        
        strengthElement.classList.add('show');
        
        let strength = 0;
        let text = '弱';
        
        // 长度检查
        if (password.length >= 8) strength++;
        if (password.length >= 12) strength++;
        
        // 包含数字
        if (/\d/.test(password)) strength++;
        
        // 包含小写字母
        if (/[a-z]/.test(password)) strength++;
        
        // 包含大写字母
        if (/[A-Z]/.test(password)) strength++;
        
        // 包含特殊字符
        if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;
        
        // 设置强度样式和文本
        strengthFill.className = 'strength-fill';
        if (strength <= 2) {
            strengthFill.classList.add('weak');
            text = '弱';
        } else if (strength <= 3) {
            strengthFill.classList.add('fair');
            text = '一般';
        } else if (strength <= 4) {
            strengthFill.classList.add('good');
            text = '良好';
        } else {
            strengthFill.classList.add('strong');
            text = '强';
        }
        
        strengthText.textContent = `密码强度：${text}`;
    }

    showInputError(inputId, message) {
        const input = document.getElementById(inputId);
        const wrapper = input.parentElement;
        
        // 移除现有错误
        this.clearInputError(input);
        
        // 添加错误样式
        wrapper.classList.add('error');
        
        // 添加错误消息
        const errorElement = document.createElement('div');
        errorElement.className = 'form-error';
        errorElement.innerHTML = `<i class="fas fa-exclamation-circle"></i> ${message}`;
        wrapper.parentElement.appendChild(errorElement);
    }

    clearInputError(input) {
        const wrapper = input.parentElement;
        const formGroup = wrapper.parentElement;
        
        wrapper.classList.remove('error', 'success');
        
        const existingError = formGroup.querySelector('.form-error');
        if (existingError) {
            existingError.remove();
        }
    }

    displayFormErrors(errors) {
        Object.keys(errors).forEach(field => {
            let inputId = field;
            
            // 映射字段名到输入框ID
            switch (field) {
                case 'username':
                    inputId = 'registerUsername';
                    break;
                case 'email':
                    inputId = 'registerEmail';
                    break;
                case 'password':
                    inputId = 'registerPassword';
                    break;
                case 'login':
                    inputId = 'loginUsername';
                    break;
            }
            
            this.showInputError(inputId, errors[field]);
        });
    }

    isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    async apiRequest(endpoint, method = 'GET', data = null) {
        const url = `${this.apiBase}/${endpoint}`;
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
            },
        };

        if (data && (method === 'POST' || method === 'PUT')) {
            options.body = JSON.stringify(data);
        }

        const response = await fetch(url, options);
        return await response.json();
    }

    saveAuthData(data) {
        if (data.session) {
            localStorage.setItem('auth_token', data.session.token);
            localStorage.setItem('auth_expires', data.session.expires_at);
            localStorage.setItem('remember_me', data.session.remember_me.toString());
        }
        
        if (data.user) {
            localStorage.setItem('user_info', JSON.stringify(data.user));
        }
    }

    checkExistingAuth() {
        const token = localStorage.getItem('auth_token');
        const expires = localStorage.getItem('auth_expires');
        
        if (token && expires) {
            const expiresDate = new Date(expires);
            if (expiresDate > new Date()) {
                // 令牌仍然有效，重定向到主页面
                window.location.href = 'index.html';
                return;
            } else {
                // 令牌已过期，清除存储
                this.clearAuthData();
            }
        }
    }

    clearAuthData() {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_expires');
        localStorage.removeItem('remember_me');
        localStorage.removeItem('user_info');
    }

    showLoading() {
        document.getElementById('loadingOverlay').classList.remove('hidden');
        
        // 禁用表单按钮
        const buttons = document.querySelectorAll('.auth-btn');
        buttons.forEach(btn => btn.disabled = true);
    }

    hideLoading() {
        document.getElementById('loadingOverlay').classList.add('hidden');
        
        // 启用表单按钮
        const buttons = document.querySelectorAll('.auth-btn');
        buttons.forEach(btn => btn.disabled = false);
    }

    showNotification(message, type = 'info') {
        const container = document.getElementById('notificationContainer');
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        let icon = 'fas fa-info-circle';
        switch (type) {
            case 'success':
                icon = 'fas fa-check-circle';
                break;
            case 'error':
                icon = 'fas fa-exclamation-circle';
                break;
            case 'warning':
                icon = 'fas fa-exclamation-triangle';
                break;
        }
        
        notification.innerHTML = `
            <div class="notification-content">
                <i class="${icon} notification-icon"></i>
                <span class="notification-message">${message}</span>
                <button class="notification-close" onclick="this.parentElement.parentElement.remove()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        container.appendChild(notification);
        
        // 自动移除通知
        setTimeout(() => {
            if (notification.parentNode) {
                notification.style.animation = 'slideOutRight 0.4s ease-out';
                setTimeout(() => notification.remove(), 400);
            }
        }, 5000);
    }
}

// 表单切换函数
function showLoginForm() {
    document.getElementById('loginForm').classList.add('active');
    document.getElementById('registerForm').classList.remove('active');
}

function showRegisterForm() {
    document.getElementById('loginForm').classList.remove('active');
    document.getElementById('registerForm').classList.add('active');
}

// 密码显示/隐藏切换
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const button = input.parentElement.querySelector('.toggle-password i');
    
    if (input.type === 'password') {
        input.type = 'text';
        button.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        button.className = 'fas fa-eye';
    }
}

// 初始化认证管理器
document.addEventListener('DOMContentLoaded', () => {
    new AuthManager();
});
